﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Transactions;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using DataAccessLayer;

namespace PresentationLayer
{
    public partial class ListCustomerNameSplit : Form
    {
        //Only DependentOnly = 1
        private int splitedCustomerID;
        private int currentMappedCustomerID;
        public int newMappedCustomerID { get; set; }

        public ListCustomerNameSplit(int currentMappedCustomerID, int splitedCustomerID)
        {
            InitializeComponent();

            try
            {
                this.splitedCustomerID = splitedCustomerID;
                this.currentMappedCustomerID = currentMappedCustomerID;

                DataTable lRec = SQLDatabase.GetDataTable("SELECT CustomerID, Description, DescriptionOfficial FROM ListCustomerName WHERE CustomerID = " + this.splitedCustomerID + " AND DistributorID <> 0 AND DependentOnly = 1 ");
                if (lRec.Rows.Count > 0)//CHECK Customer.DependentOnly = 1
                {
                    this.textBoxDescriptionSplitedCustomer.Text = (string)lRec.Rows[0]["Description"];
                    this.textBoxDescriptionOfficialSplitedCustomer.Text = (string)lRec.Rows[0]["DescriptionOfficial"];

                    //LUU Y: CHI LOAD THANG DependentOnly = 0
                    lRec = SQLDatabase.GetDataTable(" SELECT CustomerID, Description, DescriptionOfficial FROM ListCustomerName WHERE DependentOnly = 0 ORDER BY Description");

                    this.comboBoxNewMappedCustomerID.DataSource = lRec;
                    this.comboBoxNewMappedCustomerID.DisplayMember = "Description";
                    this.comboBoxNewMappedCustomerID.ValueMember = "CustomerID";
                    this.comboBoxNewMappedCustomerID.DataBindings.Add("SelectedValue", this, "newMappedCustomerID", true, DataSourceUpdateMode.OnPropertyChanged);
                }
                else
                {
                    this.splitedCustomerID = 0; this.currentMappedCustomerID = 0;
                }

                this.comboBoxNewMappedCustomerID.DataBindings.Add("Enabled", this.radioButtonMapToAnotherCustomer, "Checked", true);
                this.textBoxDescriptionNewMappedCustomer.DataBindings.Add("Enabled", this.radioButtonMapToAnotherCustomer, "Checked", true);
                this.checkBoxConfirm.DataBindings.Add("Checked", this.toolStripButtonSplitCustomer, "Enabled", true, DataSourceUpdateMode.OnPropertyChanged);
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void comboBoxNewMappedCustomerID_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.comboBoxNewMappedCustomerID.SelectedItem != null)
                {
                    DataRow dataRow = ((DataRowView)this.comboBoxNewMappedCustomerID.SelectedItem).Row;
                    if (dataRow != null && dataRow["DescriptionOfficial"] != DBNull.Value)
                        this.textBoxDescriptionNewMappedCustomer.Text = (string)dataRow["DescriptionOfficial"];
                    else
                        this.textBoxDescriptionNewMappedCustomer.Text = "";
                }
                else
                    this.textBoxDescriptionNewMappedCustomer.Text = "";
            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }

        private void toolStripButtonEscapeAndSplitCustomer_Click(object sender, EventArgs e)
        {
            try
            {

                if (sender.Equals(this.toolStripButtonSplitCustomer))
                {
                    if (this.currentMappedCustomerID == 0 || this.currentMappedCustomerID == this.newMappedCustomerID || this.splitedCustomerID == 0) return;
                    if (this.radioButtonMapToAnotherCustomer.Checked && this.newMappedCustomerID == 0) return;

                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        string customerValue;

                        //CHECK FOR VALID CUSTOMER
                        DataTable lRec = SQLDatabase.GetDataTable("SELECT TOP 1 * FROM ListCustomerName WHERE CustomerID = " + this.splitedCustomerID);
                        if (lRec.Rows.Count > 0)
                        {
                            customerValue = (string)lRec.Rows[0]["DescriptionOriginal"];
                            if (!(bool)lRec.Rows[0]["DependentOnly"] || (int)lRec.Rows[0]["DistributorID"] == 0) throw new Exception("Sorry, Can not split an UPI or a primary customer.");
                        }
                        else
                            throw new Exception("Sorry, customer could not be found.");


                        // EVENT LOG.BEGIN
                        //    If Not lSaveEventLog(ENMVNTaskID.EListCustomerName, IIf(Me.OptSplitTypeID(0), lCustomerID, lDestinationID), "", "", "", IIf(Me.OptSplitTypeID(0), EEventTakenID.ESplit, EEventTakenID.ECombine), IIf(Me.OptSplitTypeID(0), "Split: ", "Split And Combine: ") & lCustomerValue) Then GoTo ERR_HANDLER

                        //    Set lRRC = ClassConn.Execute("SELECT TOP 1 CustomerID FROM ListCustomerNameColumn WHERE DistributorID = " + lRec.Rows[0]["DistributorID") & " AND ColumnValue = N'" & lCustomerValue & "'")
                        //    If Not lRRC.BOF And Not lRRC.EOF Then If Not lSaveEventLog(ENMVNTaskID.EListCustomerName, lRRC.Fields("CustomerID"), "", "", "", EEventTakenID.ESplit, "Split " & lCustomerValue) Then GoTo ERR_HANDLER
                        // EVENT LOG.END


                        if (this.radioButtonSplitToNewCustomer.Checked)
                            if (SQLDatabase.ExecuteNonQuery("UPDATE ListCustomerName SET DependentOnly = 0 WHERE DependentOnly = 1 AND CustomerID = " + this.splitedCustomerID) != 1) throw new Exception("Sorry, unknown error!"); //TIEN CU THANH MOT CUSTOMER DOC LAP: DependentOnly = 0

                        if (SQLDatabase.ExecuteNonQuery("UPDATE ListCustomerNameColumn SET CustomerID = " + (this.radioButtonSplitToNewCustomer.Checked ? this.splitedCustomerID : this.newMappedCustomerID) + " WHERE DistributorID = " + lRec.Rows[0]["DistributorID"] + " AND ColumnValue = N'" + customerValue + "'") != 1) throw new Exception("Sorry, unknown error!"); //CHUYEN MAP VE lCustomerID NEU TIEN CU THANH STANDALONE HOAC lDestinationID NEU MAP SANG CUSTOMER KHAC

                        CommonStaticMethod.lSaveCustomerCodeMap(this.currentMappedCustomerID); //REMOVE/ ADD FOR currentMappedCustomerID
                        if (this.radioButtonMapToAnotherCustomer.Checked) CommonStaticMethod.lSaveCustomerCodeMap(this.newMappedCustomerID); //REMOVE/ ADD FOR newMappedCustomerID
                        if (this.radioButtonSplitToNewCustomer.Checked) CommonStaticMethod.lSaveCustomerCodeMap(this.splitedCustomerID);//REMOVE/ ADD FOR this.splitedCustomerID

                        // SPLIT InMarketMaster.BEGIN
                        SQLDatabase.ExecuteNonQuery("UPDATE InMarketMaster SET CustomerID = " + (this.radioButtonSplitToNewCustomer.Checked ? this.splitedCustomerID : this.newMappedCustomerID) + " WHERE DistributorID = " + lRec.Rows[0]["DistributorID"] + " AND CustomerValue = N'" + customerValue + "'"); //SPLIT CustomerID CAN CU CustomerValue
                        lRec = SQLDatabase.GetDataTable("SELECT TOP 1 * FROM ListCustomerName WHERE CustomerID = " + (this.radioButtonSplitToNewCustomer.Checked ? this.splitedCustomerID : this.newMappedCustomerID));//UPDATE FOREIGN KEY
                        if (lRec.Rows.Count > 0) SQLDatabase.ExecuteNonQuery("UPDATE InMarketMaster SET CustomerCategoryID = " + lRec.Rows[0]["CustomerCategoryID"] + ", CustomerTypeID = " + lRec.Rows[0]["CustomerTypeID"] + ", CustomerChannelID = " + lRec.Rows[0]["CustomerChannelID"] + ", CustomerGroupID = " + lRec.Rows[0]["CustomerGroupID"] + ", CustomerAddressAreaID = " + lRec.Rows[0]["AddressAreaID"] + " WHERE CustomerID = " + (this.radioButtonSplitToNewCustomer.Checked ? this.splitedCustomerID : this.newMappedCustomerID));
                        // SPLIT InMarketMaster.END

                        transactionScope.Complete();
                    }

                    CommonStaticMethod.pfCustomerDeleteOrphan(); //DELETE CUSTOMER MO COI

                    this.DialogResult = DialogResult.OK;
                }

                if (sender.Equals(this.toolStripButtonEscape))
                    this.DialogResult = DialogResult.Cancel;

            }
            catch (Exception exception)
            {
                GlobalExceptionHandler.ShowExceptionMessageBox(this, exception);
            }
        }



    }
}
